<?php
namespace app\admin\controller;

use app\common\controller\AdminBaseController;
use think\Request;
use tp5er\Backup;

/**
 *
 */
class DatabkController extends AdminBaseController
{
    /**
     * [index description]
     * @return [type] [description]
     */
    public function index()
    {
        $keywords = $this->request->param('keywords');
        $this->assign('keywords', $keywords);

        $list = array();
        $path = '.' . config('app.databk_path') . '/';
        $resource = opendir($path);
        while ($row = readdir($resource)) {
            if ($row == "." || $row == "..") {
                continue;
            }
            if (strpos($row, 'db-') === false) {
                continue;
            }
            $data['name'] = $row;
            $data['size'] = file_size_format(filesize($path . $row));
            $data['atime'] = fileatime($path . $row);
            if ($keywords == '') {
                $list[] = $data;
                continue;
            }
            if (strpos($data['name'], $keywords) !== false) {
                $list[] = $data;
                continue;
            }
        }
        $this->assign('list', $list);
        return $this->fetch();
    }

    /**
     * [create description]
     * @return [type] [description]
     */
    public function create()
    {
        $path = '.' . config('app.databk_path') . '/';
        $config = array(
            'path' => $path, //数据库备份路径
            'part' => 20971520, //数据库备份卷大小
            'compress' => 0, //数据库备份文件是否启用压缩 0不压缩 1 压缩
            'level' => 4, //数据库备份文件压缩级别 1普通 4 一般  9最高
        );

        $db = new Backup($config);
        $file = ['name' => 'db-' . date('Ymd-His'), 'part' => 1];
        $list = $db->dataList();
        foreach ($list as $key => $value) {
            $db->setFile($file)->backup($value['name'], 0);
        }
        $this->success("恭喜：备份成功!", null, '', 1);
    }

    /**
     * [delete description]
     * @param  Request $request [description]
     * @param  [type]  $name    [description]
     * @return [type]           [description]
     */
    public function delete(Request $request, $name)
    {
        self::testDel();

        $files = explode(',', $name);
        $path = '.' . config('app.databk_path') . '/';
        foreach ($files as $key => $value) {
            del_file($path . $value);
        }
        $this->success("恭喜：删除成功!", null, '', 1);
    }

    /**
     * [download description]
     * @param  Request $request [description]
     * @param  [type]  $name    [description]
     * @return [type]           [description]
     */
    public function download(Request $request, $name)
    {
        $path = '.' . config('app.databk_path') . '/' . $name;
        return download($path, $name);
    }
}
